package com.dayuanit.atm.util;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Deque;
import java.util.LinkedList;
import java.util.Properties;

public class DataBaseUtils {
	private static String url;
	private static String username;
	private static String password;
	
	private static final Deque<Connection> connList = new LinkedList<Connection>();
	
	public static synchronized Connection getConn() {
		Connection conn = connList.pollFirst();
		if (null == conn) {
			try {
				System.out.println("连接木有啦，我要睡会啦");
				Thread.sleep(2000);
				conn = connList.pollFirst();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
		if (null == conn) {
			throw new RuntimeException("连接真的没啦");
		}
		
		return conn;
	}
	
	public static synchronized void close(Connection conn) {
		if (null != conn) {
			connList.offerLast(conn);
		}
	}
	
	static {
		try {
			init();
			Class.forName("com.mysql.jdbc.Driver");
			for (int i = 0; i < 10; i ++) {
				connList.offerLast(DriverManager.getConnection(url, username, password));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private static void init() throws FileNotFoundException, IOException {
		Properties pro = new Properties();
//		pro.load(new FileInputStream(new File("D:/dayuanit/atm/resources/jdbc.properties")));
		InputStream is = DataBaseUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
		pro.load(is);
		url = pro.getProperty("jdbc.url");
		username = pro.getProperty("jdbc.username");
		password = pro.getProperty("jdbc.password");
		
		System.out.println(url + " " + username + " " + password);
	}
	
}
